package com.github.codemperor.core.token;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @author 码帝
 * @description
 * @date 2018/9/1 15:06
 */
public class JwtToken {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    public static JwtToken build() {
        return new JwtToken();
    }

    /**
     * 过期时间
     */
    private Integer expirationSeconds = 60 * 60 * 2;
    /**
     * 密钥
     */
    private String secret = "empr-pfm-admin-token-secret-v1";

    private final String USER_NAME = "USER_NAME";
    private final String USER_ROLE = "USER_ROLE";
    private final String USER_ID = "USER_ID";

    /**
     * 开启admin的token流程
     *
     * @return
     */
    public JwtToken admin() {
        this.secret = "empr-pfm-admin-token-secret-v1";
        return this;
    }

    /**
     * 开启前端用户的token流程
     *
     * @return
     */
    public JwtToken frontend() {
        this.secret = "empr-pfm-frontend-token-secret-v1";
        return this;
    }

    /**
     * 过期时间设定（秒）
     *
     * @return
     */
    public JwtToken expire(Integer expirationSeconds) {
        if (expirationSeconds != null && expirationSeconds > 0) {
            this.expirationSeconds = expirationSeconds;
        }
        return this;
    }

    /**
     * 生成token
     *
     * @return
     */
    public String create(BaseToken baseToken) {
        Date expiredDate = DateTime.now().plusSeconds(expirationSeconds).toDate();
        log.info("[createToken] tokenBean: {}, token expirationSeconds: {}, expirationDate: {}", baseToken, expirationSeconds, expiredDate);
        return Jwts.builder().setSubject("uptrade-token")
            .setExpiration(expiredDate)
            .claim(USER_ID, baseToken.getUserId())
            .claim(USER_NAME, baseToken.getUserName())
            .claim(USER_ROLE, String.join(",", baseToken.getRole()))
            .signWith(SignatureAlgorithm.HS256, secret.getBytes()).compact();
    }

    public BaseToken parseToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(secret.getBytes()).parseClaimsJws(token).getBody();
        if (null == claims) {
            return null;
        }

        BaseToken baseToken = new BaseToken();
        baseToken.setUserId(claims.get(this.USER_ID, String.class));
        baseToken.setUserName(claims.get(this.USER_NAME, String.class));
        baseToken.setStringRoleToList(claims.get(this.USER_ROLE, String.class));

        return baseToken;
    }
}
